/* ChatMessageFormatter.java
 *
 * Copyright 2011 Aleksey Konovalov
 * All Rights Reserved.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 * 
 */

package org.jimm.app;

import java.util.HashMap;
import java.util.Map.Entry;
import org.jimm.engine.Message;
import android.content.Context;
import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.format.Time;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;

/**
 * класс для форматирования строк в окне переписки
 * 
 * @author Алексей Коновалов (aleks_dsp)
 * 
 *         Использован код
 *         http://stackoverflow.com/questions/3341702/displaying-
 *         emoticons-in-android/4302199#4302199
 * 
 */
public class ChatMessageFormatter {

	private static final ForegroundColorSpan INCOMING_MESSAGE_FOREGROUND_COLOR_SPAN = new ForegroundColorSpan(
			Color.LTGRAY);
	private static final ForegroundColorSpan OUTGOING_MESSAGE_FOREGROUND_COLOR_SPAN = new ForegroundColorSpan(
			Color.YELLOW);

	// TODO сделать загрузку смайлов из смайл-паков из файлов
	
	private static final HashMap<String, Integer> emoticons = new HashMap<String, Integer>();

	static {
        emoticons.put(":)", R.drawable.smile_smile);
        emoticons.put(":-)", R.drawable.smile_smile);
        emoticons.put("=-)", R.drawable.smile_smile);
        emoticons.put("=)", R.drawable.smile_smile);
        emoticons.put(":]", R.drawable.smile_happy);
        emoticons.put(":-]", R.drawable.smile_happy);
        emoticons.put("*happy*", R.drawable.smile_happy);
        emoticons.put(":-(", R.drawable.smile_sad);
        emoticons.put(":(", R.drawable.smile_sad);
        emoticons.put("=-(", R.drawable.smile_sad);
        emoticons.put("=(", R.drawable.smile_sad);
        emoticons.put(":-P", R.drawable.smile_tongue);
        emoticons.put(":P", R.drawable.smile_tongue);
        emoticons.put("=P", R.drawable.smile_tongue);
        emoticons.put("=-P", R.drawable.smile_tongue);
        emoticons.put(":'(", R.drawable.smile_cry);
        emoticons.put(":-[", R.drawable.smile_blush);
        emoticons.put(":[", R.drawable.smile_blush);
        emoticons.put("*kissed*", R.drawable.smile_kissed);
        emoticons.put("*hi*", R.drawable.smile_hi);
        emoticons.put("*hello*", R.drawable.smile_hi);
        emoticons.put("*sorry*", R.drawable.smile_sorry);
        emoticons.put("*thumbs up*", R.drawable.smile_up);
        emoticons.put("*thumbs_up*", R.drawable.smile_up);
        emoticons.put(";-)", R.drawable.smile_wink);
        emoticons.put(";)", R.drawable.smile_wink);      
	}

	/**
	 * Ищет смайлы в строке и добавляет их
	 * 
	 * @param context
	 * @param builder
	 *            строка
	 * @param startPos
	 *            позиция символа в тексте, начиная с которого идет поиск
	 *            смайлов
	 * @param endPos
	 *            позиция символа в тексте, до которого идет поиск смайлов
	 */
	private static void detectEmotions(Context context,
			SpannableStringBuilder builder, int startPos, int endPos) {
		for (int index = startPos; index < endPos; ++index) {
			for (Entry<String, Integer> entry : emoticons.entrySet()) {
				int length = entry.getKey().length();
				if (index + length > builder.length())
					continue;
				if (builder.subSequence(index, index + length).toString()
						.equals(entry.getKey())) {
					builder.setSpan(new ImageSpan(context, entry.getValue()),
							index, index + length,
							Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
					index += length - 1;
					break;
				}
			}
		}
	}

	public static Spannable getFormattedText(Context context, Message message) {
		Time time = message.getTime();

		String dataStr = time.format("%d.%m.%Y %H:%M:%S : ");
		//TODO опциональный перенос "\n"
		String text = dataStr + "\n" + message.getText();

		SpannableStringBuilder builder = new SpannableStringBuilder(text);
		detectEmotions(context, builder, dataStr.length(), text.length());
		builder.setSpan(
				message.isReceived() ? INCOMING_MESSAGE_FOREGROUND_COLOR_SPAN
						: OUTGOING_MESSAGE_FOREGROUND_COLOR_SPAN, 0, text
						.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

		
		return builder;
	}
}
